<script setup>
import { ref, onMounted } from "vue";
import { listModelKeys, getModelConfig, setModelConfig, deleteModelConfig } from "../tauriApi";
import { useI18n } from 'vue-i18n';

const keys = ref([]);
const selectedKey = ref("");
const editingKey = ref("");
const form = ref({ base_url: "", api_key: "", model: "", headers: {}, default_temperature: null, default_max_tokens: null });
const headerKey = ref("");
const headerValue = ref("");
const loading = ref(false);
const message = ref("");
const { t } = useI18n();

async function refreshKeys() {
  keys.value = await listModelKeys();
}

async function loadSelected() {
  message.value = "";
  if (!selectedKey.value) return;
  const cfg = await getModelConfig(selectedKey.value).catch(() => null);
  if (cfg) {
    editingKey.value = selectedKey.value;
    form.value = { ...cfg, headers: cfg.headers || {} };
  }
}

function addHeader() {
  if (!headerKey.value) return;
  form.value.headers = { ...(form.value.headers || {}), [headerKey.value]: headerValue.value };
  headerKey.value = "";
  headerValue.value = "";
}

function removeHeader(k) {
  const { [k]: _omit, ...rest } = form.value.headers || {};
  form.value.headers = rest;
}

async function save() {
  if (!editingKey.value) {
    message.value = "请填写模型键名";
    return;
  }
  loading.value = true;
  try {
    await setModelConfig(editingKey.value, form.value);
    selectedKey.value = editingKey.value;
    await refreshKeys();
    message.value = "已保存";
  } catch (e) {
    message.value = String(e);
  } finally {
    loading.value = false;
  }
}

async function remove() {
  if (!selectedKey.value) return;
  await deleteModelConfig(selectedKey.value);
  selectedKey.value = "";
  editingKey.value = "";
  form.value = { base_url: "", api_key: "", model: "", headers: {}, default_temperature: null, default_max_tokens: null };
  await refreshKeys();
}

onMounted(refreshKeys);
</script>

<template>
  <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-neutral-800 dark:bg-neutral-900">
    <div class="mb-3 flex items-baseline gap-3">
      <h3 class="text-base font-semibold">{{ t ? t('app.model_config') : '模型配置' }}</h3>
      <span class="text-xs text-slate-500 dark:text-neutral-400">OpenAI compatible</span>
    </div>
    <div class="grid grid-cols-[260px_1fr] gap-4">
      <div class="flex flex-col gap-2">
        <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.saved_keys') : '已保存键值' }}</label>
        <select v-model="selectedKey" @change="loadSelected" class="h-9 rounded-md border bg-white px-2 text-sm dark:border-neutral-700 dark:bg-neutral-800">
          <option value="">{{ t ? t('model.new') : '（新建）' }}</option>
          <option v-for="k in keys" :key="k" :value="k">{{ k }}</option>
        </select>
        <button class="h-9 rounded-md bg-rose-600 text-white transition hover:bg-rose-500 disabled:opacity-50" :disabled="!selectedKey" @click="remove">{{ t ? t('model.delete') : '删除' }}</button>
      </div>
      <div class="flex flex-col gap-3">
        <div class="grid grid-cols-1 gap-3">
          <div class="flex flex-col gap-1">
            <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.key_name') : '键名' }}</label>
            <input class="h-9 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model="editingKey" placeholder="例如: openai, glm, qwen" />
          </div>
          <div class="flex flex-col gap-1">
            <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.base_url') : 'Base URL' }}</label>
            <input class="h-9 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model="form.base_url" placeholder="https://api.openai.com/v1/chat/completions" />
          </div>
          <div class="flex flex-col gap-1">
            <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.api_key') : 'API Key' }}</label>
            <input class="h-9 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model="form.api_key" placeholder="sk-..." />
          </div>
          <div class="flex flex-col gap-1">
            <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.model') : 'Model' }}</label>
            <input class="h-9 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model="form.model" placeholder="gpt-4o-mini" />
          </div>
          <div class="grid grid-cols-2 gap-3">
            <div class="flex flex-col gap-1">
              <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.default_temperature') : '默认温度 (0-2)' }}</label>
              <input type="number" step="0.1" min="0" max="2" class="h-9 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model.number="form.default_temperature" placeholder="例如 0.7" />
            </div>
            <div class="flex flex-col gap-1">
              <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.default_max_tokens') : '默认最大 Token' }}</label>
              <input type="number" step="1" min="1" class="h-9 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model.number="form.default_max_tokens" placeholder="例如 2048" />
            </div>
          </div>
        </div>

        <div class="flex flex-col gap-2">
          <label class="text-xs text-slate-500 dark:text-neutral-400">{{ t ? t('model.custom_headers') : '自定义 Headers' }}</label>
          <div class="flex items-center gap-2">
            <input class="h-9 flex-1 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model="headerKey" :placeholder="t ? t('model.header_name') : 'Header 名称'" />
            <input class="h-9 flex-1 rounded-md border bg-white px-3 text-sm dark:border-neutral-700 dark:bg-neutral-800" v-model="headerValue" :placeholder="t ? t('model.header_value') : 'Header 值'" />
            <button class="h-9 rounded-md border border-slate-200 bg-white px-3 text-sm hover:bg-slate-100 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:bg-neutral-700" @click="addHeader">{{ t ? t('model.add') : '添加' }}</button>
          </div>
          <div v-if="form.headers && Object.keys(form.headers).length" class="flex flex-wrap gap-2">
            <div v-for="(v, k) in form.headers" :key="k" class="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-slate-100 px-3 py-1 text-xs text-slate-700 dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-200">
              <span>{{ k }}: {{ v }}</span>
              <button class="ml-1 rounded px-1 text-[10px] hover:bg-white/30" @click="removeHeader(k)">✕</button>
            </div>
          </div>
        </div>

        <div class="flex items-center gap-3">
          <button class="h-9 rounded-md bg-indigo-600 px-4 text-sm text-white transition hover:bg-indigo-500 disabled:opacity-50" :disabled="loading" @click="save">{{ loading ? (t ? t('model.saving') : '保存中...') : (t ? t('model.save') : '保存') }}</button>
          <span class="text-xs text-slate-500 dark:text-neutral-400">{{ message || (t ? t('model.saved') : '') }}</span>
        </div>
      </div>
    </div>
  </div>
  
</template>

<style scoped>
</style>


